package com.central.scheduler.service.alert;

import com.central.scheduler.remote.NettyRemotingClient;
import com.central.scheduler.remote.command.Command;
import com.central.scheduler.remote.command.alert.AlertSendRequestCommand;
import com.central.scheduler.remote.command.alert.AlertSendResponseCommand;
import com.central.scheduler.remote.config.NettyClientConfig;
import com.central.scheduler.remote.utils.Host;
import com.central.scheduler.remote.utils.JsonSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Tindy
 * @date 2021/10/25
 * @describe
 */
public class AlertClientService {
    private static final Logger logger = LoggerFactory.getLogger(AlertClientService.class);

    private final NettyClientConfig clientConfig;

    private final NettyRemotingClient client;

    private volatile boolean isRunning;

    private String host;

    private int port;
    /**
     * request time out
     */
    private static final long ALERT_REQUEST_TIMEOUT = 10 * 1000L;

    /**
     * alert client
     */
    public AlertClientService(String host, int port) {
        this.clientConfig = new NettyClientConfig();
        this.client = new NettyRemotingClient(clientConfig);
        this.isRunning = true;
        this.host = host;
        this.port = port;
    }

    /**
     * close
     */
    public void close() {
        this.client.close();
        this.isRunning = false;
        logger.info("alter client closed");
    }

    /**
     * alert sync send data
     * @param groupId
     * @param title
     * @param content
     * @return
     */
    public AlertSendResponseCommand sendAlert(int groupId, String title, String content) {
        return this.sendAlert(this.host,this.port,groupId,title,content);
    }
    /**
     * alert sync send data
     * @param host host
     * @param port port
     * @param groupId groupId
     * @param title title
     * @param content content
     * @return AlertSendResponseCommand
     */
    public AlertSendResponseCommand sendAlert(String host, int port, int groupId, String title,  String content) {
        logger.info("sync alert send, host : {}, port : {}, groupId : {}, title : {} ", host, port, groupId, title);
        AlertSendRequestCommand request = new AlertSendRequestCommand(groupId, title, content);
        final Host address = new Host(host, port);
        try {
            Command command = request.convert2Command();
            Command response = this.client.sendSync(address, command, ALERT_REQUEST_TIMEOUT);
            if (response != null) {
                return JsonSerializer.deserialize(response.getBody(), AlertSendResponseCommand.class);
            }
        } catch (Exception e) {
            logger.error("sync alert send error", e);
        } finally {
            this.client.closeChannel(address);
        }
        return null;
    }
}
